﻿// See https://aka.ms/new-console-template for more information
// https://www.cnblogs.com/ittranslator/p/net-5-console-app-with-dependency-injection-serilog-logging-and-appsettings.html
// https://zhuanlan.zhihu.com/p/716518324
// https://zhuanlan.zhihu.com/p/717614088
using Huioo.Learning.Serilog.ConsoleApp.App;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog;

//console.writeline("hello, world!");

var host = AppStartup();

var dataService = ActivatorUtilities.CreateInstance<DataService>(host.Services);

dataService.Connect();

// 检查应用程序运行的当前目录，找到并加载 'appsetting.json'，
// 然后添加环境变量，这些环境变量会覆盖 appsettings.json 中的配置 
static void BuildConfig(IConfigurationBuilder builder)
{
    builder.SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddEnvironmentVariables();
}

static IHost AppStartup()
{
    var builder = new ConfigurationBuilder();
    BuildConfig(builder);

    // 定义 Serilog 配置
    Log.Logger = new LoggerConfiguration()  //初始化 Logger 配置
        .ReadFrom.Configuration(builder.Build()) //将 Serilog 连接到我们的配置
        .Enrich.FromLogContext() //从装入的 Serilog 向日志添加更多信息
        .WriteTo.Console() //决定在哪里显示日志
        .CreateLogger(); //初始化 Logger

    Log.Logger.Information("Application Starting");

    // 初始化依赖注入容器
    var host = Host.CreateDefaultBuilder() //初始化 Host 
                .ConfigureServices((context, services) => //向容器添加服务
                {
                    services.AddTransient<IDataService, DataService>(); //AddTransient 意味着每次请求都会创建一个实例。
                })
                .UseSerilog() //添加 Serilog
                .Build(); //构建 Host

    return host;
}

